<template>
  <div>
    <a-modal :title="type == 'add' ? '添加角色' : '编辑角色'" :visible="visible" @before-open="open" @before-ok="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" width="500px" :mask-closable="false">
      <div>
        <a-form auto-label-width ref="formRef" size="medium" :model="form" :rules="rules">
          <a-space direction="vertical" :size="24">
            <a-row>
              <a-col :span="24">
                <a-form-item field="roleName" label="角色名称：">
                  <a-input v-model="form.roleName" :max-length="10" show-word-limit allow-clear />
                </a-form-item>
                <a-form-item label="描述：">
                  <a-textarea v-model="form.description" placeholder="请输入" allow-clear />
                </a-form-item>
              </a-col>
            </a-row>
          </a-space>
        </a-form>
      </div>

      <template #footer>
        <a-button class="gray-outline" @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="loading" @click="handleOk">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs } from 'vue'
  import { createRole, updateRole } from '@/api/system'
  import { Message } from '@arco-design/web-vue'
  import _ from 'lodash-es'
  export default defineComponent({
    props: ['type', 'info'],
    setup(props: any, { emit }) {
      let visible = ref(false)
      const formRef = ref()
      const data: any = reactive({
        form: {},
        rules: {
          roleName: [{ required: true, message: '请输入角色名称' }],
        },
        loading: false,
        houseList: [],
      })

      const open = () => {
        if (props.type == 'edit') data.form = _.cloneDeep(props.info)
        console.log(props.info)
      }
      const handleOk = () => {
        formRef.value.validate(async (valid: any) => {
          if (!valid) {
            data.loading = true
            if (props.type == 'add') {
              const res: any = await createRole(data.form)
              if (res.code == 'SUCCESS') {
                handleCancel()
                Message.success('角色新建成功')
                emit('save')
              }
            } else {
              const res: any = await updateRole(data.form)
              if (res.code == 'SUCCESS') {
                handleCancel()
                Message.success('角色编辑成功')
                emit('save')
              }
            }
            data.loading = false
          }
        })
      }

      const handleCancel = () => {
        data.form = {}
        formRef.value.clearValidate()
        formRef.value.resetFields()
        visible.value = false
      }
      return {
        ...(toRefs(data) as any),
        visible,
        formRef,
        open,
        handleOk,
        handleCancel,
      }
    },
  })
</script>

<style lang="less" scoped></style>
